import { hex_md5 } from './md5.js';
import { pathToBase64, base64ToPath } from './base64.js';

module.exports = {
	com_set_config() {
		let _config = null;

		// #ifdef APP-PLUS
		_config = getApp().globalData.app_init;
		// #endif

		// #ifndef APP-PLUS
		_config = this;
		// #endif

		return _config;
	},
	com_getonce(callback) {
		let _this = this;
		if (!_this.change_var.once_req) {
			callback && callback();
			_this.change_var.once_req = true;
		}
	},
	com_var_req(event) {
		let { var_req = false, suc = false, fail = false } = event;

		if (var_req) {
			suc && suc();
		} else {
			fail && fail();
		}
	},

	async com_select_file(v) {
		let _this = this;

		// #ifdef APP-PLUS
		const lemonjkFileSelect = uni.requireNativePlugin('lemonjk-FileSelect');

		_this.change_var.isSelectFile = true;
		return new Promise((resolve, reject) => {
			console.log(lemonjkFileSelect, 'lemonjkFileSelect');
			lemonjkFileSelect.showPicker(
				{
					//各属性配置见下方【showPicker可配置参数说明】
					pathScope: '/Download',
					mimeType: 'audio/mpeg',
					utisType: 'public.mp3',
					loadingToast: 'no',
					filterConfig: {
						//对象里配置的属性要同时满足
						// fileName:['base.apk','config.txt','配置文件.yaml'],  //属性数组满足其中一项
						// fileSize:String(1*1024*1024),  //byte 单位：字节
						fileExtension: ['mp3'], //属性数组满足其中一项
					},
				},
				async result => {
					console.log(result, 'result');
					_this.change_var.isSelectFile = false;
					if (result.code == '0') {
						let path = _this.objJudge(result.files) ? result.files[0].filePath : false;
						resolve(path);
					} else {
						resolve(false);
					}

					// if (result.code == 1001) {
					// 	uni.showModal({
					// 		title: '需要文件访问权限',
					// 		content: '您还未授权本应用读取文件。为保证您可以正常上传文件，请在权限设置页面打开文件访问权限（不同手机厂商表述可能略有差异）请根据自己手机品牌设置',
					// 		confirmText: '去授权',
					// 		cancelText: '算了',
					// 		success(e) {
					// 			if (e.confirm) {
					// 				// 跳转到应用设置页
					// 				// lemonjkFileSelect.gotoSetting();
					// 			}
					// 		},
					// 	});
					// }
				}
			);
		});
		// #endif
	},

	async com_upload_old(v) {
		let _this = this;
		let { url = '/base/upload', type, path, callback } = v;
		// console.log(path, 'path');
		let str = await _this.pathToBase64_fun(path);
		let _back = await _this.com_getdata({
			url,
			data_handle_on: false,
			data: {
				type,
				str,
			},
			header: { 'Content-Type': 'application/json' },
			timeout: 30000,
		});
		// console.log(_back, 'com_upload');
		return _back;
	},
	com_upload(config) {
		let _this = this;
		let { url = '/base/upload_file', type, path, progress = false } = config;
		let _config = _this.com_set_config();
		let req_url = _config.apiUrl + _config.apiFilename + url;
		if (type) {
			req_url += `?type=${type}`;
		}
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: req_url,
				filePath: path,
				name: 'file',
				timeout: _config.timeout,

				success(res) {
					let data = JSON.parse(res.data);
					resolve(data);
				},
				fail(res) {
					resolve(false);
				},
			}).onProgressUpdate(res => {
				progress && progress(res);
			});
		});
	},

	com_init_data(res) {
		let _this = this;

		for (const key in res) {
			let element = res[key];
			let _type = _this.gettype(element);
			// console.log(_type, res[key], key);
			switch (_type) {
				case null:
					res[key] = '--';
					break;
				case undefined:
					res[key] = '--';
					break;
				// case String:
				// 	if (!_this.objJudge(res[key])) {
				// 		res[key] = '--';
				// 		console.log(_type, res[key], key);
				// 		debugger;
				// 	}
				// 	break;
			}
		}
		return res;
	},

	com_getdata(e) {
		let {
			url,
			data = {},
			data_handle_on = false, //作加密处理
			method = 'POST',
			data_fun,
			fail_fun,
			complete_fun,
			id_name = '',
			mode = 'default',
			timeout = 0,
			header = false,
			show_log = false,
			show_data = false,
		} = e;
		let _this = this;

		let _config = this.com_set_config();

		if (id_name) {
			let user_id = uni.getStorageSync('userid') || '';
			data[id_name] = user_id;
		}

		if (data_handle_on) {
			data = _this.data_handle(data);
		}

		if (_this.show_log || show_log) {
			// console.log(`com_getdata:${JSON.stringify(data)}---${JSON.stringify(url)}`);
			console.log(url);
			console.log(data);
		}

		let req_url = _config.apiUrl + _config.apiFilename + url;

		if (mode == 'pay') {
			// 支付接口
			req_url = _config.apiUrl + url;
		} else if (mode == 'network') {
			//  外链
			req_url = url;
		}
		if (header) {
			header = _this.header_handle(header);
		} else {
			header = _this.header_handle(_config.headers);
		}
		if (timeout == 0) {
			timeout = _config.timeout;
		}
		// console.log(header);
		return new Promise((resolve, reject) => {
			uni.request({
				header,
				url: req_url,
				data,
				method,
				timeout,
				success(res) {
					let data = res.data;
					// #ifdef APP
					data = _this.com_init_data(data);
					// #endif
					if (_this.show_data || show_data) {
						console.log(data);
					}
					if (data_fun) {
						data_fun && data_fun(data);
					}
					resolve(data);
					_this.$forceUpdate();
				},
				fail(res) {
					if (fail_fun) {
						fail_fun && fail_fun();
					}
					resolve(false);
				},
				complete() {
					if (complete_fun) {
						complete_fun();
					}
				},
			});
		});
	},

	com_getlist(e) {
		let {
			url,
			data = this.page_form,
			load_name = 'loadingstatus',
			form_name = 'page_form',
			export_name = 'page_list',
			id_name = '',
			before_req_fun, //请求前
			before_fun, //处理前
			callback, //处理后
			fail_fun, //失败回调
			complete_fun, //最后回调
			data_handle_on = true, // 作加密处理
			method = 'POST',
			_datakey = 'data',
		} = e;
		let _this = this;
		let _config = this.com_set_config();
		// console.log(_this[load_name], 'com_getlist--loadingstatus');
		if (_this[load_name] == 1 || _this[load_name] == 2) return;
		_this[load_name] = 1;
		if (id_name) {
			let user_id = uni.getStorageSync('userid') || '';
			data[id_name] = user_id;
		}

		if (data_handle_on) {
			data = _this.data_handle(data);
		}
		before_req_fun && before_req_fun();
		return new Promise((resolve, reject) => {
			uni.request({
				header: _this.header_handle(_config.headers),
				data,
				method,
				timeout: _config.timeout,
				url: _config.apiUrl + _config.apiFilename + url,
				success(res) {
					let _resdata = res.data;
					// let total = _this[form_name].count = data.count;
					let back_count = _this.objJudge(_resdata[_datakey]) ? _resdata[_datakey].length : 0;

					// if (_this.objJudge(_resdata[_datakey])) {
					if (_resdata.state == 1) {
						before_fun && before_fun(_resdata);

						if (_this[form_name].page == 1) {
							_this[export_name] = _resdata[_datakey];
						} else {
							_resdata[_datakey].forEach(element => {
								_this[export_name].push(element);
							});
						}

						if (_this[form_name].limit <= back_count) {
							_this[load_name] = 0;
							_this[form_name].page = parseInt(_this[form_name].page) + 1;
						} else {
							setTimeout(() => {
								_this[load_name] = 2;
							}, 300);
						}

						callback && callback(_this[export_name]);
						resolve(true);
					} else {
						setTimeout(() => {
							_this[load_name] = 2;
						}, 300);
					}
				},
				fail: res => {
					if (fail_fun) {
						fail_fun();
					} else {
					}
					resolve(false);
				},
				complete() {
					if (complete_fun) {
						complete_fun();
					} else {
					}
				},
			});
		});
	},

	//  loding -> 成功 失败
	//  成功带不带icon  失败带不带icon
	// 通用加载
	com_loading(e) {
		/* status 1 开始 0 直接隐藏 2成功 */
		let {
			k = 'nextreq',
			title = '请稍候...',
			mask = true,
			time = 1000,
			hide_time = 0,
			duration = 2000,
			icon = 'success',
			type = 'loading',
			status = 1,
			throttle = false, //默认关闭节流阀
			throttle_tips = false,
			loading_log = false,
			callback = false,
		} = e;
		let _this = this;
		let _f = _this[k];
		if (loading_log) {
			console.log(e);
			console.log('com_loading变量状态----------------------------------', _f, ' 状态', status);
		}
		if (throttle) {
			if (status == 1) {
				if (!_f) {
					if (throttle_tips) {
						uni.showToast({
							title: '请稍等片刻再试~',
							duration,
							icon: 'none',
						});
					}
					// 节流阀
					return false;
				}
				_this[k] = false;
			} else {
				// 高频操作使用 time 限制
				if (time > 0) {
					setTimeout(() => {
						_this[k] = true;
					}, time);
				} else {
					_this[k] = true;
				}
			}
		}
		switch (status) {
			case 0:
				// 0 直接隐藏
				if (hide_time > 0) {
					setTimeout(() => {
						callback && callback();
						uni.hideLoading();
					}, hide_time);
				} else {
					callback && callback();
					uni.hideLoading();
				}
				break;
			case 1:
				// 1 开始
				if (type == 'loading') {
					// 开始显示loading
					uni.showLoading({
						title,
						mask,
					});
				} else if (type == 'msg') {
					_this.com_msg(title);
				} else if (type == 'none') {
				}
				break;
			case 2:
				// 2 成功
				if (title) {
					uni.showToast({
						title,
						duration,
						icon,
					});
				} else {
					uni.hideLoading();
				}
				if (callback) {
					if (hide_time > 0) {
						setTimeout(() => {
							callback && callback();
						}, hide_time);
					} else {
						callback && callback();
					}
				}
				break;
		}

		return true;
	},
	// 加载初始化事件
	// 0 最后结束初始化页面
	// 1 开始显示加载中
	// 2 接口处理根据 state成功与否返回 成功提示或者返回错误信息msg
	com_loading_fun(config = {}) {
		let _this = this;
		let {
			mode = 1,
			k = 'nextreq',
			title = '加载中...',
			hide_time = 300,
			judge_var = 'repeat_once',
			repeat_loding = false,
			suc_callback = false,
			fail_callback = false,
			suc_icon = 'success',
			fail_icon = 'none',
			show_fail_msg = true,
			response = false,
		} = config;
		let END_TITLE = title;
		if (mode == 0) {
			// 结束加载数据loading2
			_this.change_var['timeout_loading'] = false;
			_this.com_loading({
				status: 0,
				k,
				hide_time: 200,
				time: 0,
				throttle: true,
				callback() {
					typeof _this.render_req == 'undefined' ? false : (_this.render_req = true);
					_this.pulldownJudge();
					suc_callback && suc_callback();
					_this.get_view_info({
						viewNmae: '#page_main_id',
						viewCallBack(_info) {
							if (_this.objJudge(_info) && _this.objJudge(_info.height)) {
								_this.change_var['page_height'] = _this.pxTorpx(_info.height);
							}
						},
					});
				},
			});
		} else if (mode == 1) {
			if (repeat_loding) {
				// 重复显示加载
				_this.com_loading({ status: 1, k, title, mask: true, throttle: false });
				_this.change_var['timeout_loading'] = true;
			} else {
				// 只提示一次
				if (_this.change_var[judge_var]) {
					_this.change_var[judge_var] = false;
					_this.change_var['timeout_loading'] = true;
					_this.com_loading({
						status: 1,
						k,
						title,
						mask: true,
						throttle: false,
					});
				}
			}
			setTimeout(() => {
				if (_this.change_var['timeout_loading']) {
					_this.com_loading_fun({ mode: 0, throttle: true });
				}
			}, _this.timeout);
		} else if (mode == 2) {
			let { code, msg = '网络请求错误', data } = response;
			let END_ICON = 'none';
			let END_CALLBACK = false;
			if (state == 1) {
				END_CALLBACK = suc_callback(response);
				END_ICON = suc_icon;
			} else {
				END_CALLBACK = fail_callback;
				END_ICON = fail_icon;
				if (show_fail_msg) {
					END_TITLE = msg;
				} else {
					END_TITLE = false;
				}
			}
			_this.com_loading({ status: 2, k, title: END_TITLE, throttle: true, icon: END_ICON, hide_time, callback: END_CALLBACK });
		}
	},

	com_clearlist(e = {}) {
		let {
			load_name = 'loadingstatus',
			form_name = 'page_form',
			list_name = 'page_list',
			callback, //处理函数
		} = e;

		let _this = this;
		_this[load_name] = 0;
		if (_this.objJudge(_this[form_name]['limit'])) {
			_this[form_name].page = 1;
		}
		// _this[list_name] = [];
		callback && callback();
	},

	com_maxpage(e) {
		let { total, limit } = e;
		//计算最大页码
		let maxpage = parseInt(total / limit);
		if (total / limit - maxpage > 0) maxpage++;
		return maxpage;
	},
	// 通用提示
	com_msg(title, duration = 2000, mask = false, icon = 'none') {
		//统一提示方便全局修改
		if (Boolean(title) === false) {
			return;
		}
		uni.showToast({
			title,
			duration,
			mask,
			icon,
		});
	},
	// 返回上一页
	com_page_back(delta = 1, url = '') {
		let _this = this;
		if (url) {
			// console.log('3')
			_this.goweburl_f(url, 2);
		} else {
			// console.log('4')
			let routes = getCurrentPages();
			if (routes.length == 1) {
				// console.log('5')
				_this.goweburl_f('/pages/index/index');
			} else {
				uni.navigateBack({
					delta,
				});
			}
		}
	},

	// 价格
	com_price(x) {
		if (!x) {
			x = 0;
		}
		var f = parseFloat(x);
		if (isNaN(f)) return false;
		var f = Math.round(x * 100) / 100;
		var s = f.toString();
		var rs = s.indexOf('.');
		if (rs < 0) {
			rs = s.length;
			s += '.';
		}
		while (s.length < rs + 1 + 2) {
			s += '0';
		}
		var leftNum = s.split('.')[0];
		var rightNum = '.' + s.split('.')[1];
		var result;
		var resultArray = new Array();
		if (leftNum.length > 3) {
			var i = true;
			while (i) {
				resultArray.push(leftNum.slice(-3));
				leftNum = leftNum.slice(0, leftNum.length - 3);
				if (leftNum.length < 4) {
					i = false;
				}
			}
			var sortArray = new Array();
			for (var i = resultArray.length - 1; i >= 0; i--) {
				sortArray.push(resultArray[i]);
			}
			result = leftNum + ',' + sortArray.join(',') + rightNum;
		} else {
			result = s;
		}
		return result;
	},
	// 数组排序
	com_sort_list(_list, key, mode) {
		// mode asc 正序 desc 倒序
		// 正序  [1, 3, 100]
		// 倒序 [100, 3, 1]

		// key 关键字段
		return _list.sort((p, n) => {
			let _p = isNaN(parseFloat(p[key])) ? 0 : parseFloat(p[key]);
			let _n = isNaN(parseFloat(n[key])) ? 0 : parseFloat(n[key]);
			if (mode == 'asc') {
				return _p < _n ? -1 : _p > _n ? 1 : 0;
			} else if (mode == 'desc') {
				return _p < _n ? 1 : _p > _n ? -1 : 0;
			}
		});
	},

	//  数组重组
	com_arr_classify(config) {
		let _this = this;
		let { _list, classify_key, classify_name = 'name', classify_list_name = 'list', o_fun = false, n_fun = false } = config;
		//  classify_key => 数组项中的key名筛选条件
		let check_shop = {};
		let i = 0;
		return _list.reduce((_p, _n) => {
			let _key = _n[classify_key];
			let o = {};
			if (!check_shop[_key]) {
				check_shop[_key] = {
					index: i,
				};

				// { name:classify_key ,list:[next,next,next,next]}

				o[classify_name] = _key;
				o[classify_list_name] = [];

				_p.push(o);
				i++;
			}
			_p[check_shop[_key].index][classify_list_name].push(_n);
			let can_fun = _this.objJudge(check_shop[_key]);
			if (o_fun && can_fun) {
				o = _p[check_shop[_key].index];
				_p[check_shop[_key].index] = o_fun(o);
			}
			// if (n_fun) {
			//     _n = n_fun(_n);
			// }
			// console.log(check_shop, 'check_shop')
			return _p;
		}, []);
		// [{ name:classify_key ,list:[next,next]},{ name:classify_key ,list:[next,next]}]
	},

	com_change_var(v, time = 0) {
		let _this = this;
		if (!this.nextreq) return;
		this[v] = !this[v];
		this.nextreq = false;
		if (time > 0) {
			setTimeout(() => {
				_this.nextreq = true;
			}, time);
		} else {
			_this.nextreq = true;
		}
	},

	com_modal(e = {}) {
		let { title = '', content = '确认执行该操作？', confirmText = '确认', cancelText = '取消', showCancel = true } = e;
		let _this = this;
		return new Promise((resolve, reject) => {
			let config = {
				confirmText,
				cancelText,
				showCancel,
				success(res) {
					if (res.confirm) {
						resolve(true);
					} else {
						resolve(false);
					}
				},
			};
			if (title) {
				config['title'] = title;
			}
			if (content) {
				config['content'] = content;
			}
			// console.log(config);
			uni.showModal(config);
		});
	},

	com_pagelogin_initcallback() {
		let _this = this;
		setTimeout(() => {
			_this.render_component_init = true;
		}, 300);
	},

	com_onshow_fun() {
		let _this = this;
		_this.change_var.page_canshow = true;
		let _caninit = true;

		if (!_this.render_component_init) _caninit = false;
		if (_this.change_var.isScanning || _this.change_var.isPay || _this.change_var.isSelectFile) _caninit = false;
		if (_caninit) {
			// console.log(_this.change_var);
			_this.$refs.pagelogin.component_init();
		}
	},

	com_page_hide(_this) {
		_this.change_var.page_canshow = false;
		// console.log('com_page_hide');
		// console.log(`${_this.change_var.page_canshow}--隐藏页面`)
	},
	com_page_unload(_this) {
		_this.change_var.page_canshow = false;
	},
	// 卸载页面时需要停止播放音频
	com_page_destory(d) {
		let play_context = typeof d;
		console.log(play_context, d);
		if (play_context == 'undefined') {
		} else {
			d.pause();
			d.destroy();
		}
	},
	// 页面高度如果大于屏幕高度取默认值
	// 页面高度如果小于屏幕高度取 两者差值
	get_pageScrollTop_targe(config) {
		let _this = this;
		let targe = 0;
		let _default = config.scrollTop_targe;
		let _page = config.page_height - config.win_height;
		// console.log(_default, config);
		return _page > _default ? _default : _page;
	},

	get_view_info(config) {
		let _this = this;
		let { viewNmae, viewCallBack } = config;
		const query = uni.createSelectorQuery().in(_this);
		query.select(viewNmae)
			.boundingClientRect(data => {
				viewCallBack && viewCallBack(data);
			})
			.exec();
	},

	module_judge_render() {
		let _this = this;
		let refs = this.$refs;

		clearTimeout(_this.login_components_task);
		_this.login_components_task = setTimeout(() => {
			// console.log('1');
			if (refs.pagelogin) {
				// console.log('2');
				let filter_ref = ['diynav', 'mybtns']; // 需要进行运算的组件ref名
				let checks = {};
				let n = 0; // 登录渲染前的异步数量
				let iname = '';
				let tname = '';
				for (const k in refs) {
					let item = refs[k];
					// console.log(k, 'k')
					if (filter_ref.indexOf(k) != -1) {
						tname += tname ? `,${k}` : k;
						_this.$set(checks, k, item);
						// checks[k] = item;
						// console.log(item.render, 'item')
						if (_this.objJudge(item.render) && item.render == 1) {
							n++;
							iname += iname ? `,${k}` : k;
						}
					}
				}
				// console.log(`组件渲染后回调--module_judge_render--加载完${n}个,${iname}，一共${Object.keys(checks).length}个,${tname}`)
				if (n == Object.keys(checks).length && _this.render_req == false) {
					//    执行登录组件初始化
					// console.log(refs['pagelogin'], ' refs')

					console.log('judge_______________');
					refs['pagelogin'].component_init();
				}
			}
		}, 300);
	},
	rpxTopx(rpx) {
		const screenWidth = uni.getSystemInfoSync().screenWidth;
		let v = Number.parseInt(rpx) / (375 / screenWidth);
		return parseFloat(v.toFixed(0));
	},
	pxTorpx(px) {
		const screenWidth = uni.getSystemInfoSync().screenWidth;
		// 750
		let v = (750 * Number.parseInt(px)) / screenWidth;
		return parseFloat(v.toFixed(0));
	},
	back_number(v, w = 2) {
		let _this = this;
		let type = _this.gettype(v);

		if (type == 'String') {
			if (v == '--') {
				return '--';
			} else {
				return parseFloat(parseFloat(v).toFixed(w));
			}
		} else if (type == 'Number') {
			return parseFloat(v.toFixed(w));
		} else {
			return 0;
		}
	},

	back_fixed(v, w = 2) {
		return v.toFixed(w);
	},

	// 获取缓存
	get_cache() {
		let k = uni.getStorageInfoSync().currentSize;
		// let t = uni.getStorageInfoSync();
		// console.log(t)

		let txt = '';
		if (k <= 1024) {
			txt = '';
			// } else if (k < 1024) {
			//     txt = k + "B";
		} else if (k < 1048576) {
			txt = (k / 1024).toFixed(2) + 'KB';
		} else if (k < 1073741824) {
			txt = (k / 1048576).toFixed(2) + 'MB';
		} else {
			txt = (k / 1073741824).toFixed(2) + 'GB';
		}
		return txt;
	},

	// 清除缓存
	async clear_cache(item) {
		let _this = this;
		let f = await this.com_modal({
			content: '确认清除缓存？',
		});
		if (!f) return;
		if (
			!_this.com_loading({
				status: 1,
				title: '清除中...',
			})
		)
			return;
		let t = uni.getStorageInfoSync();
		// console.log(JSON.stringify(t.keys), t.keys)
		let filter_key = ['base_customer_phone', 'usertoken', 'userid', 'userinfo'];

		t.keys.reduce((p, n) => {
			// console.log(p, n, p.indexOf(n), 't.keys')
			if (p.indexOf(n) == -1) {
				uni.removeStorageSync(n);
			}
			return p;
		}, filter_key);

		setTimeout(() => {
			_this.com_loading({
				status: 2,
				title: '清除成功',
			});
			_this.judge_view(item);
		}, 1000);
	},

	// http://test.h5.qijiniu.com/web/?id=789#/h5/share
	// 获取h5地址栏参数
	getQueryVariable() {
		// token=xx&id=1
		let url = window.location.search.substring(1);
		console.log(url);
		return this.getQueryData(url);
	},

	getQueryData(url) {
		let parameter = url.split('&');
		// ['token=xx','id=1']
		let DATA = {};
		for (let index = 0; index < parameter.length; index++) {
			let element = parameter[index];
			let str_index = element.indexOf('=');
			let k = element.slice(0, str_index);
			let v = element.slice(str_index + 1);
			DATA[k] = v;
		}
		// console.log(DATA);
		return DATA;
	},

	goweburl_f(url, tt = 0, title = '') {
		let _this = this;
		let _config = this.com_set_config();

		if (!_config.routerclick) {
			return false;
		}

		if (!url || url.length < 4) {
			return false;
		}
		_config.routerclick = false;
		url = url.trim();
		if (tt == 100) {
			_config.routerclick = true;

			if (url) {
				// this.getLiveInfo(url)
				this.goVideoIndex(url);
			}
		} else {
			if (url.substring(0, 4) == 'http') {
				// #ifdef APP-PLUS
				plus.runtime.openURL(url);
				_config.routerclick = true;
				// #endif

				// #ifdef MP
				uni.navigateTo({
					url: `/pages/index/goviews?path=${encodeURIComponent(url)}`,
					fail(res) {},
					complete() {
						_config.routerclick = true;
					},
				});
				// #endif

				// #ifdef H5
				window.location.href = url;
				_config.routerclick = true;
				// #endif
			} else if (url.substring(0, 1) == '/') {
				if (tt == 2) {
					uni.redirectTo({
						url: url,
						complete() {
							_config.routerclick = true;
						},
					});
				} else {
					uni.navigateTo({
						url: url,
						fail(res) {
							_config.routerclick = true;
							uni.switchTab({
								url: url,
								complete() {
									_config.routerclick = true;
								},
							});
						},
						complete() {
							_config.routerclick = true;
						},
					});
				}
			} else {
				_config.routerclick = true;
			}
		}

		if (title) {
			uni.setNavigationBarTitle({
				title: title,
			});
		}
	},
	fortprice(value = 0) {
		if (!value) {
			value = 0;
		}
		value = value * 1;
		if (isNaN(value)) return 0;
		return value.toFixed(2);
	},

	// 比较时间返回时间戳
	compare_time(start, end, mode = 'default') {
		// mode 默认显示 x年x月x天

		let sDate, eDate, sTime, eTime, diff, year, month, day, minute;
		let _back = null;
		// 开始时间
		if (start) {
			sDate = new Date(start);
		} else {
			sDate = new Date();
		}

		// 结束时间
		if (end) {
			eDate = new Date(end);
		} else {
			eDate = new Date();
		}

		sTime = sDate.getTime();
		eTime = eDate.getTime();

		// 相差的时间
		if (eTime > sTime) {
			diff = eTime - sTime;
		} else {
			return -1;
		}
		year = Math.floor(diff / (1000 * 60 * 60 * 24 * 365));
		month = Math.floor(diff / (1000 * 60 * 60 * 24 * 30));
		day = Math.floor(diff / (1000 * 60 * 60 * 24));

		if (mode == 'year') {
			_back = year;
		}
		if (mode == 'day') {
			_back = day;
		}

		if (mode == 'default') {
			_back = diff;
		}
		return _back;
	},

	// 比较限定时间 来重新定义执行回调事件的定时器.
	// 防止过快触发查询事件
	recurring_task_judge(config, callback = false, return_callback = false) {
		// need_diff 需要隔多久才执行回调
		let { cache_name, need_diff = 10000 } = config;
		// 取缓存条件时间进行计算 进行定时任务
		let _this = this;
		let task_config = uni.getStorageSync('task_config') || {};
		let cache_time = null;
		let now_time = new Date().getTime();
		let cache_diff = null;
		let fun_time = need_diff;
		if (_this.objJudge(task_config[cache_name])) {
			// 取上一次触发的时间
			cache_time = task_config[cache_name];
			// '2024-3-5 10:20:04', '2024-3-5 10:20:00'
			cache_diff = now_time - cache_time; // 4000
			// 10000, 4000
			if (need_diff > cache_diff) {
				fun_time = need_diff - cache_diff;
			} else {
				fun_time = 300;
			}
		} else {
			fun_time = 100;
		}
		console.log(_this.happenTimeFun(cache_time, 'y-m-d h:i:s'), cache_diff, fun_time);
		if (callback) {
			clearTimeout(_this.recurring_task);
			_this.recurring_task = setTimeout(() => {
				callback();
				task_config[cache_name] = new Date().getTime();
				uni.setStorageSync('task_config', task_config);
			}, fun_time);
		}

		if (return_callback) {
			if (fun_time > 300) {
				return_callback();
			}
		}
	},
	timeJudge(TIME_TARGET) {
		let _this = this;
		let _DATE = null;
		let _CONFIG = null;
		// 1字符串 2数字时间戳
		let IS_STRING = true;
		if (!_this.objJudge(TIME_TARGET)) return false;
		// 检查是否是数字
		if (typeof TIME_TARGET === 'number' && !isNaN(TIME_TARGET)) {
			// 检查是否在合理的时间范围内
			let isNum = TIME_TARGET >= 0 && TIME_TARGET < new Date().setFullYear(3000);
			if (isNum) {
				IS_STRING = false;
			}
		}
		if (IS_STRING == 1) {
			// 根据字符串初始化
			_DATE = new Date(TIME_TARGET);
			if (!_this.isValidDate(_DATE)) {
				TIME_TARGET = TIME_TARGET.replace(/T/g, ' '); //去掉T
				TIME_TARGET = TIME_TARGET.replace(/-/g, '/');
				TIME_TARGET = TIME_TARGET.replace(/\.\d+/, ' '); //去掉毫秒
				_DATE = new Date(TIME_TARGET);
			}
		} else {
			// 根据时间戳初始化
			_DATE = new Date(TIME_TARGET);
		}
		_CONFIG = {
			// 获取结束时间的年月日时分秒
			year: _DATE.getFullYear(),
			month: _DATE.getMonth() + 1,
			day: _DATE.getDate(),
			hour: _DATE.getHours(),
			minute: _DATE.getMinutes(),
			second: _DATE.getSeconds(),
			getTime: _DATE.getTime(),
		};
		return _CONFIG;
	},
	// 时间初始化 几秒前 几分钟前
	// 1分钟内 显示 '刚刚'
	// 60分钟内 显示 'xx分钟前'
	initAccurateTime(timer) {
		let _this = this,
			NOW_DATE,
			TARGET_DATE,
			NOW_TIME,
			NOW_YEAR,
			NOW_DAY,
			init_second = 1000,
			init_minute = init_second * 60,
			init_hour = init_minute * 60,
			init_day = init_hour * 24,
			diff_second,
			diff_minute,
			diff_hour,
			diff_day,
			DIFF,
			TEXT;
		NOW_DATE = new Date();
		TARGET_DATE = _this.timeJudge(timer);
		if (!TARGET_DATE) return;
		NOW_TIME = NOW_DATE.getTime();
		NOW_YEAR = NOW_DATE.getFullYear();
		NOW_DAY = NOW_DATE.getDate();

		let { year, month, day, hour, minute, second, getTime: TRAGET_TIME } = TARGET_DATE;
		let show_month = _this.append_zero(month);
		let show_day = _this.append_zero(day);
		let show_hour = _this.append_zero(hour);
		let show_minute = _this.append_zero(minute);

		DIFF = NOW_TIME - TRAGET_TIME;

		diff_day = Math.floor(DIFF / init_day);
		diff_hour = Math.floor(DIFF / init_hour);
		diff_minute = Math.floor(DIFF / init_minute);
		diff_second = Math.ceil(DIFF / init_second);
		// console.log(NOW_DAY, day);
		if (day + 1 == NOW_DAY) {
			// 昨天
			// console.log(DIFF, init_day, diff_day);
			TEXT = `昨天 ${show_hour}:${show_minute}`;
		} else if (diff_hour < 24 && diff_hour >= 1) {
			TEXT = `${diff_hour} 小时前`;
		} else if (diff_minute < 60 && diff_minute >= 1) {
			TEXT = `${diff_minute} 分钟前`;
		} else if (diff_second < 60 && diff_second >= 1) {
			// TEXT = `${diff_second}秒前`;
			TEXT = '刚刚';
		} else if (NOW_YEAR == year) {
			// 同一年 省略年份
			TEXT = `${show_month}-${show_day} ${show_hour}:${show_minute} `;
		} else if (NOW_YEAR != year) {
			TEXT = `${year}-${show_month}-${show_day} ${show_hour}:${show_minute} `;
		}
		// console.log(TEXT);
		// console.log({ diff_day, diff_hour, diff_minute, diff_second, DIFF });
		// console.log(TARGET_DATE);
		return TEXT;
	},

	append_zero(n) {
		return n >= 0 && n < 10 ? '0' + n : '' + n;
	},

	// 时间初始化
	happenTimeFun(num, types = 'y-m-d h:i', dd = 1) {
		let _this = this;
		if (!num) {
			return '';
		}
		// 1字符串 2数字时间戳
		let num_type = 1;
		// 检查是否是数字
		if (typeof num === 'number' && !isNaN(num)) {
			// 检查是否在合理的时间范围内
			let isNum = num >= 0 && num < new Date().setFullYear(3000);
			if (isNum) {
				num_type = 2;
			} else {
				return;
			}
		}

		let zthisTime;
		let date;

		if (num_type == 1) {
			// 根据字符串初始化
			zthisTime = num + '+0800';
			date = new Date(zthisTime);

			if (!this.isValidDate(date)) {
				num = num.replace(/T/g, ' '); //去掉T
				num = num.replace(/-/g, '/');
				num = num.replace(/\.\d+/, ' '); //去掉毫秒
				date = new Date(num);
			}

			// zthisTime = num;
			// if (dd == 1) {

			//     if (_this.gettype(num) == 'String') {
			//         zthisTime = num.replace(/-/g, '/');

			//     }
			// }
			// date = new Date(zthisTime);
			// if (!this.isValidDate(date)) {
			//     date = new Date(num);
			// }
		} else {
			// 根据时间戳初始化
			date = new Date(num);
			// console.log(num)
			// console.log(date)
		}

		let y = date.getFullYear();
		let MM = date.getMonth() + 1;
		MM = MM < 10 ? '0' + MM : MM;
		let d = date.getDate();
		d = d < 10 ? '0' + d : d;
		let h = date.getHours();
		h = h < 10 ? '0' + h : h;
		let m = date.getMinutes();
		m = m < 10 ? '0' + m : m;
		let s = date.getSeconds();
		s = s < 10 ? '0' + s : s;

		if (types == 'y-m-d h:i:s') {
			return `${y}-${MM}-${d} ${h}:${m}:${s}`;
		} else if (types == 'y/m/d h:i:s') {
			return `${y}/${MM}/${d} ${h}:${m}:${s}`;
		} else if (types == 'h:i') {
			return h + ':' + m;
		} else if (types == 'y-m-d_text') {
			return `${y}年${MM}月${d}日`;
		} else if (types == 'y-m-d h:i') {
			return `${y}-${MM}-${d} ${h}:${m}`;
		} else if (types == 'y.MM.dd hh.i') {
			return `${y}.${MM}.${d} ${h}:${m}`;
		} else if (types == 'y-m-d') {
			return `${y}-${MM}-${d}`;
		} else if (types == 'y/MM/dd') {
			return `${y}/${MM}/${d}`;
		} else if (types == 'y') {
			return `${y}`;
		} else if (types == 'MM') {
			return `${MM}`;
		} else if (types == 'dd') {
			return `${d}`;
		} else if (types == 'h:i:s') {
			return h + ':' + m + ':' + s;
		} else if (types == 'ms') {
			return `${m}m ${s}s`;
		} else if (types == 'ms_txt') {
			return `${m}分${s}秒`;
		} else {
			return `${y}/${MM}/${d} ${h}:${m}`;
		}
	},

	// 时间戳转 年月日时分秒
	timestamp_show_fun(timing, types = 1) {
		let hour = Math.floor(timing / 1000 / 60 / 60);
		let minute = Math.floor((timing / 1000 / 60) % 60);
		let seconds = Math.floor((timing / 1000) % 60);
		let _back = null;
		switch (types) {
			case 1:
				_back = `${hour}H ${minute}m ${seconds}s`;
				break;
			case 2:
				_back = `${hour}小时${minute}分`;
				break;
		}

		return _back;
		// if (targetTime - nowTime > 1000) {
		//     this.timer = true;
		//     this.hour = hour;
		//     this.min = minute;
		//     this.sec = seconds;
		//     if (this.state == 1) {
		//         this.$emit("addendviews", false, this.keyindex);
		//         this.state = 2;
		//     }
		// }
	},
	isValidDate(date) {
		return date instanceof Date && !isNaN(date.getTime());
	},

	init_map_scale(range, type) {
		/*
       
       1 -> 13
       3 -> 12
       5 -> 11
       10 -> 10
type = select
        */
		let _this = this;
		if (type == 'select') {
			if (range <= 1) return 14;
			else if (range <= 3) return 13;
			else if (range <= 6) return 12;
			else if (range <= 10) return 11;
		} else {
			if (range <= 1) return 13;
			else if (range <= 3) return 12;
			else if (range <= 5) return 11;
			else if (range <= 10) return 10;
		}
	},

	init_map(o, type = 'list') {
		let _this = this;
		let v = _this.deepclone(o);

		//  v.fence_range 半径公里数 如1km -> 1
		let radius = v.fence_range * 1000;

		let color = 'rgba(31,209,194,0.31)';
		let fillColor = 'rgba(31,209,194,0.31)';
		if (type == 'list') {
		} else {
			color = '#1fd1c24f';
			fillColor = '#1fd1c24f';
		}
		let circles = [
			{
				latitude: parseFloat(v.fence_lat),
				longitude: parseFloat(v.fence_lng),
				color,
				fillColor,
				radius,
				strokeWidth: 0,
			},
		];
		_this.$set(v, 'circles', circles);

		let _range = v.fence_range;
		let _scale = 0;

		// if (type == 'select') {
		//     _this.$set(v, 'scale', 12)
		// } else {
		//     _scale = _this.init_map_scale(_range)
		//     _this.$set(v, 'scale', _scale)
		// }
		_scale = _this.init_map_scale(_range, type);
		_this.$set(v, 'scale', _scale);
		return v;
	},

	getindex(e) {
		let _this = this;
		let i = -1;
		let { key = 'id', value, list = 'page_list' } = e;
		for (let index = 0; index < _this[list].length; index++) {
			const element = _this[list][index];
			if (element[key] == value) {
				i = index;
				break;
			}
		}
		return i;
	},

	swiperchange(e) {
		// console.log('开始切换');
		this.$set(this.swiper_dots, e.target.id, e.detail.current);
		// can_set_newindex =  e.detail.current;
		// this.swiper_dots[`${e.target.id}`] = e.detail.current;
		// this.$forceUpdate();
	},

	// 校验表单项返回结果 true false
	// phone name
	page_check(v, check_v, k = 'nextreq') {
		let _this = this;

		let ele = _this.COMMON_VAR.page_check_config[check_v];

		if (!ele) return;
		let t_null = ele.tips_null;
		let t_fail = _this.objJudge(ele.tips_fail) ? ele.tips_fail : t_null;

		if (!v) {
			// 空提示
			_this.com_msg(t_null);
			_this[k] = true;
			return false;
		}
		let re_name = ele.regular;

		if (_this.objJudge(re_name)) {
			// 需要正则验证
			if (!_this[re_name].test(v)) {
				_this.com_msg(t_fail);
				_this[k] = true;
				return false;
			}
		}
		return true;
	},
	startPulldownJudge(type) {
		let _this = this;
		if (type == 1) {
			_this.change_var.pulldown = 1;
			if (_this.objJudge(_this.$refs.paging)) {
			} else {
				_this['change_var']['repeat_once'] = true;
			}
		}
		_this.com_clearlist();
	},
	// 停止下拉刷新
	pulldownJudge() {
		let _this = this;
		if (_this.change_var.pulldown == 1) {
			_this.change_var.pulldown = 0;
			if (_this.objJudge(_this.$refs.paging)) {
				_this.$refs.paging.complete();
			}
			uni.stopPullDownRefresh();
		}
	},
	// 倒计时
	RemainTime(isend = false) {
		let _this = this;
		// _this.send_req = true;
		// console.log(_this.iTime, 'viTimeiTime')
		let iTime = _this.iTime,
			iTime_task = _this.iTime_task;
		let iSecond,
			sSecond = '',
			iMinute,
			sTime = '';

		if (iTime >= 0) {
			iSecond = parseInt(iTime % 60);
			iMinute = parseInt(iTime / 60);
			if (iSecond >= 0) {
				if (iMinute > 0) {
					sSecond = iMinute + '分' + iSecond + 'S';
				} else {
					sSecond = iSecond + 'S';
				}
			}
			sTime = sSecond;
			if (iTime <= 0) {
				clearTimeout(_this.iTime_task);
				_this.iTime_task = null;
				sTime = '重新发送';
				_this.iTime = _this.change_var.page_iTime;
				_this.send_req = true;
			} else {
				if (isend) {
					clearTimeout(_this.iTime_task);
					_this.iTime_task = null;
					_this.iTime = _this.change_var.page_iTime;
					sTime = '获取验证码';
				} else {
					_this.iTime_task = setTimeout(function () {
						_this.RemainTime();
					}, 1000);
					_this.iTime = iTime - 1;
				}
			}
		} else {
			sTime = '没有倒计时';
		}
		_this.code_tips = sTime;
	},

	clear_task(v) {
		clearTimeout(v);
	},
	//图片放大
	com_previewImage(config) {
		let _this = this;
		let { urls, current, key = false } = config;
		let urls_list = urls.reduce((p, n) => {
			let imgSrc = '';
			if (_this.objJudge(n[key]) && key) {
				imgSrc = n[key];
			} else if (_this.objJudge(n['image'])) {
				imgSrc = n['image'];
			} else {
				imgSrc = n;
			}
			p.push(imgSrc);
			return p;
		}, []);
		// console.log(current);
		// console.log(urls_list);
		uni.previewImage({
			urls: urls_list,
			current,
		});
	},
	// 匹配富文本的视频链接和图片链接
	mateVideoImage(html, split = ',') {
		let _this = this;
		let IMAGE = '';
		let VIDEO = '';
		let RICH_TEXT = '';

		if (html) {
			// --------------------------------------------------------------
			let image_match = [...html.matchAll(/<img\s+src="([^"]+)"/g)];
			image_match.forEach(match => {
				IMAGE += IMAGE ? `${split}${match[1]}` : match[1];
			});
			// --------------------------------------------------------------

			// --------------------------------------------------------------
			let video_match = [...html.matchAll(/<source\s+src="([^"]+)"/g)];
			video_match.forEach(match => {
				VIDEO += VIDEO ? `${split}${match[1]}` : match[1];
			});
			// --------------------------------------------------------------

			RICH_TEXT = html.replace(/<div\s+data-w-e-type="video"[\s\S]*?<\/div>/g, '');
			RICH_TEXT = RICH_TEXT.replace(/<p><img[\s\S]*?\/><\/p>/g, '');
		}

		// console.log(IMAGE, VIDEO, RICH_TEXT);
		return { IMAGE, VIDEO, RICH_TEXT };
	},

	formatRichText(html) {
		if (!html) {
			return '';
		}
		let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
			match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
			match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
			match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
			return match;
		});
		newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
			match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
			return match;
		});
		newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:inline-block;"');
		return newContent;
	},
	//判断微信版本
	compareVersion(v1, v2) {
		v1 = v1.split('.');
		v2 = v2.split('.');
		const len = Math.max(v1.length, v2.length);
		while (v1.length < len) {
			v1.push('0');
		}
		while (v2.length < len) {
			v2.push('0');
		}
		for (let i = 0; i < len; i++) {
			const num1 = parseInt(v1[i]);
			const num2 = parseInt(v2[i]);
			if (num1 > num2) {
				return 1;
			} else if (num1 < num2) {
				return -1;
			}
		}
		return 0;
	},

	// 滚动到对应表单
	getscrollTop(what) {
		let _this = this;
		const query = uni.createSelectorQuery().in(_this);
		query.select(what)
			.boundingClientRect(data => {
				// let top = data.top + _this.pagescrollTop - _this.header_hight - 30;
				// if (top < 0) top = 0;
				console.log(data);
				uni.pageScrollTo({
					scrollTop: '854',
					duration: 500,
				});
			})
			.exec();
		return false;
	},

	// 计算公里数
	get_distance(e) {
		let { p_lat, p_lng, n_lat, n_lng } = e;

		let EARTH_RADIUS = 6378.137; // 地球半径
		let radLat1 = (p_lat * Math.PI) / 180.0; //p_lat * Math.PI / 180.0=>弧度计算
		let radLat2 = (n_lat * Math.PI) / 180.0;
		let a = radLat1 - radLat2;
		let b = (p_lng * Math.PI) / 180.0 - (n_lng * Math.PI) / 180.0;
		let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
		s = s * EARTH_RADIUS;
		s = Math.round(s * 10000) / 10; // 输出为米
		// return {
		//     m: s * 1000,
		//     km: Number(s.toFixed(2))
		// }

		// console.log(e, 'get_distance', s * 1000)
		// console.log(e, 'get_distance', Number(s.toFixed(2)))

		return s;
	},
	// 计算速度
	get_speed(d, time) {
		let _s = time;
		if (d == 0 || _s == 0) {
			return 0;
		} else {
			return (d / _s) * 60 * 60;
		}
	},
	// 处理post数据
	get_post_data(obj, total_name = 'content') {
		let _this = this;
		let myinit = function (e) {
			let { obj, current_name, end_value, total_name, data, isend, islooping } = e;

			if (isend) {
				// 最后的节点了
				// total_name => 'content[con_float_electricity][el_fa_fee][0][key]' 递归拼接出来的字段名
				// end_value => 7  对应最后的值
				data[`${total_name}`] = end_value;
				// console.log({
				//     current_name,
				//     end_value,
				//     data,
				//     total_name,
				//     data,
				//     isend
				// });
			} else {
				// 还有下级 获取上此循环传入的total_name和current_name拼接

				if (islooping) total_name += current_name;

				let obj_type = Object.prototype.toString.call(obj).slice(8, -1);
				switch (obj_type) {
					case 'Undefined':
						myinit({
							current_name,
							end_value: obj,
							total_name,
							data,
							isend: true,
						});
						break;
					case 'Null':
						myinit({
							current_name,
							end_value: obj,
							total_name,
							data,
							isend: true,
						});
						break;
					case 'String':
						myinit({
							current_name,
							end_value: obj,
							total_name,
							data,
							isend: true,
						});
						break;
					case 'Number':
						myinit({
							current_name,
							end_value: obj,
							total_name,
							data,
							isend: true,
						});
						break;
					case 'Boolean':
						myinit({
							current_name,
							end_value: obj,
							total_name,
							data,
							isend: true,
						});
						break;
					case 'Array':
						if (obj.length == 0) {
							myinit({
								current_name,
								end_value: JSON.stringify(obj),
								total_name,
								data,
								isend: true,
							});
						} else {
							for (let i = 0; i < obj.length; i++) {
								myinit({
									obj: obj[i],
									current_name: `[${i}]`,
									end_value,
									total_name,
									data,
									isend,
									islooping: true,
								});
							}
						}
						break;
					case 'Object':
						if (!_this.objJudge(obj)) {
							myinit({
								current_name,
								end_value: JSON.stringify(obj),
								total_name,
								data,
								isend: true,
							});
						} else {
							for (let k in obj) {
								myinit({
									obj: obj[k],
									current_name: `[${k}]`,
									end_value,
									total_name,
									data,
									isend,
									islooping: true,
								});
							}
						}

						break;
				}
			}
			return data;
		};
		return myinit({
			obj,
			data: {},
			total_name,
			isend: false,
			islooping: false,
		});
	},

	async pathToBase64_fun(path) {
		return await pathToBase64(path);
	},
	// base64 加密和解密
	async base64_en(v) {
		return await this.pathToBase64_fun(v);
	},
	// base64_de(v) {
	//     return base64ToPath(v)
	// },
	// 加密
	data_handle(v) {
		// console.log(JSON.stringify(v), v, '_this.data_handle(v)')
		// MeEnybtPM%#PEDYGnCuEzhkjmzc2S@NG 前后端规定的密钥
		// v 传递过来的数据结构 进行json转义后再md5加密
		let d = {
			jsonstr: JSON.stringify(v),
			token: hex_md5('MeEnybtPM%#PEDYGnCuEzhkjmzc2S@NG' + JSON.stringify(v)),
		};
		// console.log(JSON.stringify(d), d.token, 'd.token')
		return d;
	},
	// 百度地图坐标转换腾讯地图
	bMapToQQMap(lng, lat) {
		if (lng == null || lng == '' || lat == null || lat == '') return [lng, lat];

		var x_pi = (3.14159265358979324 * 3000.0) / 180.0;
		var x = parseFloat(lng) - 0.0065;
		var y = parseFloat(lat) - 0.006;
		var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
		var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
		var lng = (z * Math.cos(theta)).toFixed(12) * 1;
		var lat = (z * Math.sin(theta)).toFixed(12) * 1;
		return [lng, lat];
	},

	// 换腾讯地图坐标转百度地图
	qqMapToBMap(lng, lat) {
		if (lng == null || lng == '' || lat == null || lat == '') return [lng, lat];

		var x_pi = (3.14159265358979324 * 3000.0) / 180.0;
		var x = parseFloat(lng);
		var y = parseFloat(lat);
		var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
		var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
		var lng = (z * Math.cos(theta) + 0.0065).toFixed(12);
		var lat = (z * Math.sin(theta) + 0.006).toFixed(12);
		return [lng, lat];
	},

	// 权限判断显示
	roleJudge(v) {
		let _this = this;
		let { user_status = 0 } = _this.USER_MSG;

		// 禁止查看
		let dis_show_config = {
			// 普通用户禁止查看压差 单串以及设置参数
			0: [
				'dev_diff',
				'index_voltage_chart',
				'current_calibration',
				'voltage_calibration',
				'reset_capacity',
				'initialize',
				'protection_parameters',
				'protection_count',
				'current_setting',
				'temperature_setting',
				'balanced_setting',
				'capacity_voltage_setting',
				'link_resistance',
				'function_setting',
				'system_setting',
			],
			// 管理员
			1: [],
			// 经销商 只能看
			2: [],
			4: [
				'current_calibration',
				'voltage_calibration',
				'reset_capacity',
				'initialize',
				'protection_parameters',
				'protection_count',
				'current_setting',
				'temperature_setting',
				'balanced_setting',
				'capacity_voltage_setting',
				'link_resistance',
				'function_setting',
				'system_setting',
			],
		};

		let my_config = dis_show_config[user_status];
		let key = v.key || v.form_key || v.view_type;
		// console.log(key);
		if (_this.objJudge(my_config)) {
			if (my_config.indexOf(key) > -1) {
				return false;
			} else {
				return true;
			}
		} else {
			return true;
		}
	},

	// 数据判空
	objJudge(obj) {
		let result = Object.prototype.toString.call(obj).slice(8, -1);
		// console.log(obj, result, 'objJudge')
		switch (result) {
			case 'Undefined':
				return false;
				break;
			case 'Null':
				return false;
				break;
			case 'Object':
				// return JSON.stringify(obj) !== '{}'
				return Object.keys(obj).length != 0;
				break;
			case 'Array':
				return obj.length !== 0;
				break;
			case 'ArrayBuffer':
				return obj.byteLength !== 0;
				break;
			case 'String':
				return obj !== '' && obj !== '--' && obj !== '-';
				// && obj !== '0'
				break;
			case 'Number':
				return true;
				break;
			case 'Boolean':
				return obj;
				break;
		}
	},

	// 查看密码强度
	getLvl(pwd) {
		let lvl = 0; //默认是0级
		//密码中是否有数字,或者是字母,或者是特殊符号
		if (/[0-9]/.test(pwd)) {
			lvl++;
		}
		//判断密码中有没有字母
		if (/[a-zA-Z]/.test(pwd)) {
			lvl++;
		}
		//判断密码中有没有特殊符号
		if (/[^0-9a-zA-Z_]/.test(pwd)) {
			lvl++;
		}
		return lvl; //1 3
	},

	callphone(e) {
		let phone = e;

		if (Object.prototype.toString.call(phone).slice(8, -1) == 'Number') {
			phone = phone.toString();
		}
		uni.makePhoneCall({
			phoneNumber: phone,
		});
	},
	// 跳转客服
	customer_wechat() {
		let _this = this;
		uni.share({
			provider: 'weixin',
			openCustomerServiceChat: true,
			customerUrl: 'https://work.weixin.qq.com/kfid/kfcd1ccda887b892d83', //企业微信地址
			corpid: 'wwbffeed0d77f3a4ac', //企业id
			success: res => {
				console.log('success:234' + JSON.stringify(res));
			},
			fail: err => {
				let { errCode } = err;
				switch (errCode) {
					case -8:
						_this.com_msg('请安装微信客户端');
						break;
				}
			},
		});
	},

	copydata(data) {
		let _this = this;
		if (!_this.objJudge(data)) return;
		uni.setClipboardData({
			data,
			success: res => {
				_this.com_msg('复制成功');
			},
			fail: res => {},
		});
	},

	//校验tonken
	async getusertoken() {
		let _this = this;

		let { token } = this.getQueryVariable();

		let user_res = await _this.com_getdata({
			url: '/base.ashx',
			data: {
				Action: 'user_info',
				token,
			},
			data_fun: function (res) {
				if (res.state == 1) {
					_this.page_list = res.coupon_list;
					_this.page_data = {
						nickname: res.nickname,
						less_money: res.less_money,
					};
				} else {
				}
				_this.com_loading_fun({ mode: 0 });
			},
		});
		if (user_res.state == 1) {
			_this.set_user(user_res, 'user_info');
		}
		return true;

		// let usertoken = uni.getStorageSync('usertoken');
		// let { state } = await _this.com_getdata({
		// 	url: '/login/token',
		// 	data_handle_on: false,
		// 	method: 'GET',
		// 	data: {
		// 		token: usertoken,
		// 	},
		// });

		// if (state == 1) {
		// 	let user_res = await _this.com_getdata({
		// 		url: '/user/info',
		// 		id_name: 'id',
		// 	});
		// 	if (user_res.state == 1) {
		// 		_this.set_user(user_res, 'user_info');
		// 	}
		// 	return true;
		// } else if (state == -2) {
		// 	_this.clear_user('-2');
		// 	return false;
		// } else {
		// 	return false;
		// }
	},

	check_update() {
		let _this = this;
		// #ifdef MP-WEIXIN
		const updateManager = wx.getUpdateManager(); //1. 检查小程序是否有新版本发布
		updateManager.onCheckForUpdate(function (res) {
			console.log(res);
			// 请求完新版本信息的回调
			if (res.hasUpdate) {
				//2. 小程序有新版本，则静默下载新版本，做好更新准备
				updateManager.onUpdateReady(function () {
					wx.showModal({
						title: '更新检测',
						content: '检测到新版本，即将重启小程序？',
						showCancel: false,
						success: function (res) {
							if (res.confirm) {
								//3. 新的版本已经下载好，调用applyUpdate应用新版本并重启
								updateManager.applyUpdate();
							} else if (res.cancel) {
								//不应用
							}
						},
					});
				});
			}
		});
		// #endif
	},

	set_user(v, type = 'check') {
		let _this = this;
		let target = {};
		if (type == 'login') {
			uni.setStorageSync('usertoken', v.data);
			target = v.info;
		} else if (type == 'user_info') {
			// 检查token并且更新用户信息
			Object.assign(target, v.data);
		}

		if (_this.objJudge(target)) {
			uni.setStorageSync('userid', target.id);
			if (_this.objJudge(target.user_openid)) {
				uni.setStorageSync('openid', target.user_openid);
			}
			let is_normal_user = false;
			if (target.user_status == 0) {
				is_normal_user = true;
			}
			uni.setStorageSync('is_normal_user', is_normal_user);

			_this.store_set_state_config({ state_name: 'USER_MSG', data: target });
			_this.store_set_state({ state_name: 'USER_LOGIN', state_value: true });

			// console.log(_this.USER_MSG);
			// console.log(target);
		}
	},

	loginJudge() {
		let usertoken = uni.getStorageSync('usertoken');
		if (!usertoken) {
			return -1;
		} else {
			return 1;
		}
	},

	com_padding_fun(_arr) {
		let _this = this;
		let _n = _arr.length;
		let _back = _arr;
		let target = _this.COMMON_VAR.safeAreaInsets_bot;
		if (target > 0) {
			switch (_n) {
				case 1:
					_back = [_arr[0], _arr[0], target];
					break;
				case 2:
					_back = [_arr[0], _arr[1], target];
					break;
				case 3:
					_back = [_arr[0], _arr[1], target];
					break;
				case 4:
					_back = [_arr[0], _arr[1], target, _arr[2]];
					break;
			}
		}
		return _back;
	},

	padding_judge_safe(_arr) {
		let _this = this;
		let _n = _arr.length;
		let _back = _arr;
		let target = _this.COMMON_VAR.safeAreaInsets_bot;
		if (target > 0) {
			let _bot = 0;
			switch (_n) {
				case 1:
					_bot = _arr[0] > target ? _arr[0] : target;
					_back = [_arr[0], _arr[0], _bot];
					break;
				case 2:
					_bot = _arr[0] > target ? _arr[0] : target;
					_back = [_arr[0], _arr[1], _bot];
					break;
				case 3:
					_bot = _arr[2] > target ? _arr[2] : target;
					_back = [_arr[0], _arr[1], _bot];
					break;
				case 4:
					_bot = _arr[2] > target ? _arr[2] : target;
					_back = [_arr[0], _arr[1], _bot, _arr[3]];
					break;
			}
		}
		let padding = '';
		if (_back.length > 0) {
			_back.forEach(v => {
				padding += padding ? ` ${v}rpx` : `${v}rpx`;
			});
		}
		return padding;
	},

	set_pagetop(vv) {
		let _this = this;
		_this.page_render = false;
		_this.change_var.page_top = vv;
		_this.page_render = true;
		_this.module_judge_render();
		_this.change_var.page_content_top = _this.change_var.page_top + _this.change_var.page_nav;
	},
	set_pagebot(vv) {
		let _this = this;
		_this.change_var.page_bot = vv;
		_this.module_judge_render();
	},
	set_pagetab(vv) {
		let _this = this;
		if (this.objJudge(vv)) {
			_this.change_var.page_nav = vv;
			_this.change_var.page_content_top = _this.change_var.page_top + _this.change_var.page_nav;
		}
	},
	// 主动登录
	async zhudon_login(url, modal = true) {
		let _this = this;
		if (_this.loginJudge() == -1) {
			if (modal) {
				let _flag = await _this.com_modal({ title: `提示`, content: '您当前状态尚未登录', confirmText: '马上登录' });
				if (_flag) {
					if (_this.$refs.pagelogin) {
						if (url) {
							uni.setStorageSync('login_to_url', url);
						}
						_this.$refs.pagelogin.page_login();
					}
				} else {
					return false;
				}
			} else {
				if (_this.$refs.pagelogin) {
					if (url) {
						uni.setStorageSync('login_to_url', url);
					}
					_this.$refs.pagelogin.page_login();
				}
			}

			return false;
		} else {
			_this.goweburl_f(url);
			return true;
		}
	},
	// 更新列表单项
	listUpdateItem(e) {
		let { list = 'page_list', index, data, weburl, handle } = e;

		let _this = this;
		let _config = this.com_set_config();
		let usertoken = uni.getStorageSync('usertoken');
		data.usertoken = usertoken;
		uni.request({
			header: _config.headers,
			data,
			method: 'POST',
			url: _config.apiUrl + _config.apiFilename + weburl,
			success(res) {
				let data = res.data;

				// debugger
				if (data.state == 1) {
					if (handle) {
						handle(data.data);
					} else {
						if (!data.data) {
							list.splice(index, 1);
						} else {
							list.splice(index, 1, data.data);
						}
					}
					uni.removeStorageSync('updataid');
					_this.$forceUpdate();
				} else {
					_this.com_msg(data.msg || '网络请求错误');
				}
			},
			fail(res) {
				_this.com_msg('网络请求错误');
			},
		});
	},

	check_pic_all(newurl) {
		// , oss_style = "?x-oss-process=style/750_auto"
		// let _this = this;
		// if (!newurl) {
		//     return '';
		// } else if (newurl.length < 4) {
		//     return newurl
		// } else if ((newurl.substring(0, 4) == "http" || newurl.substring(0, 1) == "/") && newurl.indexOf(_this
		//         .oss_url) == -1 && newurl.indexOf('?x-oss-process=') == -1) {

		//     return newurl;
		// } else {
		//     let url = newurl.substr(newurl.length - 3);
		//     if (url == 'gif' || url == 'GIF') {
		//         oss_style = '';
		//     }
		//     let r = '';
		//     if (newurl.indexOf(_this.oss_url) == -1) {
		//         r = _this.oss_url + newurl;
		//         // debugger
		//     } else {
		//         r = newurl;
		//     }
		//     if (newurl.indexOf('?x-oss-process=') == -1) {
		//         r += (oss_style != -1 ? oss_style : '');
		//     } else {
		//         r = newurl;
		//     }
		//     return r
		// }

		return newurl;
	},

	// 处理成轮播数据 四个一组
	arrTonum(arr, num) {
		let parArr = [];
		let sonArr = [];
		arr.forEach((item, index) => {
			sonArr.push(item);
			if (sonArr.length == num || index == arr.length - 1) {
				parArr.push(sonArr);
				sonArr = [];
			}
		});
		return parArr;
	},

	gettype(obj) {
		let result = Object.prototype.toString.call(obj).slice(8, -1);
		if (result === 'Null') {
			return null;
		} else if (result === 'Undefined') {
			return undefined;
		} else {
			return result;
		}
	},
	deepclone(obj) {
		let warp;
		let _this = this;
		// 读取类型
		let objtype = _this.gettype(obj);
		if (objtype === 'Object') {
			warp = {};
		} else if (objtype === 'Array') {
			warp = [];
		} else {
			return obj;
		}
		for (let x in obj) {
			//  得到的数据内容
			let value = obj[x];
			if (_this.gettype(value) === 'Object' || _this.gettype(value) === 'Array') {
				warp[x] = _this.deepclone(value);
			} else {
				warp[x] = obj[x];
			}
		}
		return warp;
	},
	async logout_fun(callback = 'refresh') {
		let _this = this;
		let f = await _this.com_modal({
			content: '确认退出登录？',
		});
		if (f) {
			_this.clear_user(callback);
		}
	},
	//过滤手机号码 s 开始位置 n 星星个数
	changePhone(value, s = 3, n = 4) {
		if (value) {
			let len = value.length;
			let x = value.substring(s + n);
			let k = value.substring(0, s);
			let star = new Array(n).fill('*').join('');
			let values = k + star + x;
			return values;
		} else {
			return '';
		}
	},

	get_address_detail(v, type = 'detail') {
		if (type == 'detail') {
			return `${v.province}${v.city}${v.district}${v.street}`;
		}
	},
	// 十六进制色值转RGB #fff 或者 #ffffff   255,255,255
	hexadecimalToRgb(v) {
		let _this = this;
		let hexa_arr = v.substring(1).match(/.{1,2}/g);
		let t_arr = hexa_arr.map(item => {
			return _this.stt(item);
		});
		let hex = t_arr.join(',');
		return hex;
	},
	// 十六进制转十进制
	stt(vv, tt = 16) {
		return parseInt(vv, tt);
	},

	/**
	 * 十六进制转二进制数组
	 * @param {number} vv 十进制数字 1001
	 * @param {number} nn 数组长度 1byte对应8位  2byte对应16位
	 * @returns Array
	 */
	sttwo(vv, nn = 16, end = true) {
		let _data = this.tts(vv);
		var bitsArray = new Array(nn);
		for (var i = 0; i < nn; i++) {
			if (end) {
				// 高位在后 13 -> 1011
				bitsArray[i] = (_data >> i) & 1;
			} else {
				// 高位在前 13 -> 1101
				bitsArray[nn - 1 - i] = (_data >> i) & 1;
			}
		}
		return bitsArray;
	},
	back_setting() {
		return new Promise((r, j) => {
			uni.getSetting({
				success(res) {
					r(res.authSetting);
				},
			});
		});
	},

	ceil_number(num, tt = 10) {
		// 将数字向上取整
		let roundedNum = Math.ceil(num);
		// 如果数字的个位不为 0，则将数字加上差值以确保个位为 0
		if (roundedNum % tt !== 0) {
			roundedNum += tt - (roundedNum % tt);
		}
		return roundedNum;
	},

	// 取规则校验数据
	com_test_check(value, key) {
		let _this = this;
		let _config = _this.COMMON_VAR.page_check_config[key];
		let regular = _config.regular;

		if (_this.objJudge(regular)) {
			return _this[regular].test(value);
		}
	},
	// 批量校验
	com_page_check(o) {
		let _this = this;
		let { keys_config, form } = o;
		let pass = true;
		for (let index = 0; index < keys_config.length; index++) {
			let { check_key, null_tips, error_tips = false, check_fun = false } = keys_config[index];
			if (!error_tips) {
				error_tips = null_tips;
			}
			if (!form[check_key]) {
				// 空提示
				_this.com_msg(null_tips);
				pass = false;
				break;
			}
			if (check_fun) {
				let _c = check_fun(form[check_key]);

				if (_c) {
				} else {
					_this.com_msg(error_tips);
					pass = false;
					break;
				}
			}
		}
		return pass;
	},

	// 经纬度地址解析
	com_getaddress(v) {
		let _this = this;
		let _config = this.com_set_config();
		let { latitude, longitude } = v;
		let data = {
			key: _config.map_key,
			location: `${longitude},${latitude}`,
		};
		return new Promise((resolve, reject) => {
			_this.com_getdata({
				url: 'https://restapi.amap.com/v3/geocode/regeo',
				data_handle_on: false,
				mode: 'network',
				method: 'GET',
				data,
				data_fun(data) {
					if (data.status == 1) {
						resolve(data.regeocode);
					} else {
						resolve({
							formatted_address: '未知地址',
							addressComponent: false,
						});
					}
				},
			});
		});
	},

	getCenterLonLat(point1, point2) {
		let { latitude: oneLat, longitude: oneLon } = point1;
		let { latitude: twoLat, longitude: twoLon } = point2;
		// oneLon, oneLat, twoLon, twoLat
		//oneLon：第一个点的经度；oneLat：第一个点的纬度；twoLon：第二个点的经度；twoLat：第二个点的纬度；
		let aLon = 0,
			aLat = 0;
		let bLon = Number(oneLon) - Number(twoLon);
		let bLat = Number(oneLat) - Number(twoLat);
		//Math.abs()绝对值
		if (bLon > 0) {
			aLon = Number(oneLon) - Math.abs(bLon) / 2;
		} else {
			aLon = Number(twoLon) - Math.abs(bLon) / 2;
		}
		if (bLat > 0) {
			aLat = Number(oneLat) - Math.abs(bLat) / 2;
		} else {
			aLat = Number(twoLat) - Math.abs(bLat) / 2;
		}
		return {
			latitude: aLat,
			longitude: aLon,
		};
	},
};
